package com.bnyy.gbp;

import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ObjectUtils {

    /**
     * 判断一个实体类对象实例的所有成员变量是否为空
     *
     * @param obj 校验的类对象实例
     * @return List
     * @throws Exception
     */

    public static boolean isObjectFieldEmpty(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();  //得到类对象
        Field[] fs = clazz.getDeclaredFields(); //得到属性集合
        List<String> list = new ArrayList<>();
        for (Field field : fs) {            //遍历属性
            field.setAccessible(true); //设置属性是可以访问的（私有的也可以）
            if (field.get(obj) == null || field.get(obj) == "" || "null".equalsIgnoreCase(String.valueOf(field.get(obj)))) {
                String name = field.getName();
                list.add(name);
            }
        }
        return list.isEmpty();
    }

    /**
     * 判断对象中属性值是否全为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        boolean empty = true;
        if (null == object) {
            return empty;
        }

        try {
            Field[] declaredFields = object.getClass().getDeclaredFields();
            for (Field f : declaredFields) {
                f.setAccessible(true);
                Object o = f.get(object);

//                Log.e("checkObjAllFieldsIsNull", "name = " + f.getName() + "     obj = " + o);

                if (o instanceof List) {
                    List l = (List) o;
                    if (!l.isEmpty()) {
                        empty = false;
                        break;
                    }
                } else if (o instanceof Integer){
                    if ((Integer) o > 0) {
                        empty = false;
                        break;
                    }
                } else {
                    if (o != null && !TextUtils.isEmpty(String.valueOf(o))) {
                        empty = false;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("checkObjAllFieldsIsNull", "empty = " + empty);
        return empty;
    }
}
